import pygame
import os
from pygame.locals import *

def interpolate(array, pos, axis):
	"""interpolate a given possition messured in the the arrays native units"""
	(px,py) = pos
	ax,ay = (int(px),int(py))
	(x, y) = (px - ax,py- ay)
	
	if x < 0.5:
		if y < 0.5:
			return array[ax][ay][axis]
		else:
			return array[ax][ay+1][axis]
	else:
		if y < 0.5:
			return array[ax+1][ay][axis]
		else:
			return array[ax+1][ay+1][axis]

def load_image(name, colorkey=None, alpha = None):
	fullname = os.path.join('data', name)
	try:
		image = pygame.image.load(fullname)
	except pygame.error, message:
		print 'Cannot load image:', name
		raise SystemExit, message
	if alpha is not None:
		image = image.convert_alpha()
	else:
		image = image.convert()
	if colorkey is not None:
		if colorkey is -1:
			colorkey = image.get_at((0,0))
		image.set_colorkey(colorkey, RLEACCEL)
	return image, image.get_rect()

def arraytosurface(array, blocksize):
	(hunits, wunits, dim) = array.shape
	hunits = (hunits - 1) * blocksize
	wunits = (wunits - 1) * blocksize
	blocksize = float(blocksize)
	if array.max() < -array.min():
		max = -array.min()
	else:
		max = array.max()
	surf = pygame.Surface((hunits, wunits))
	for x in range(hunits):
		for y in range(wunits):
			px = x / blocksize
			py = y / blocksize
			i = int(interpolate(array, (px ,py), 0) / max * 128 + 128)
			j = int(interpolate(array, (px, py) , 1) / max * 128 + 128)
			if j > 255:
				j = 255
			if j < 0:
				j = 0
			if i > 255:
				j = 255
			if i < 0:
				i = 0
			color = (i,0,j,255)
			surf.set_at((x,y),color)
	return surf